﻿namespace PrismEx.Distributed.Events
{
    using System;
    using System.Management.Instrumentation;
    using System.ServiceModel;

    using Microsoft.Practices.Prism.Events;
    using Microsoft.Practices.ServiceLocation;

    using PrismEx.Distributed.Interfaces;

    public abstract class DistributedEvent<TEventType> : CompositePresentationEvent<TEventType>
        where TEventType : DistributedEvent<TEventType>
    {
        private readonly IDistributedEventChannel distributedEventChannel;

        protected DistributedEvent()
        {
            this.distributedEventChannel = ServiceLocator.Current.GetInstance<IDistributedEventChannel>();

            if (distributedEventChannel == null)
            {
                throw new InstanceNotFoundException(string.Format("Could not resolve instance of '{0}'", typeof(IDistributedEventChannel)));
            }

            var ostat = distributedEventChannel.GetProperty<IOnlineStatus>();
            ostat.Online += this.OnOnline;
            ostat.Offline += this.OnOffline;

            distributedEventChannel.Open();
        }

        public bool IsOnline { get; private set; }

        private void OnOffline(object sender, EventArgs e)
        {
            IsOnline = false;
        }

        private void OnOnline(object sender, EventArgs e)
        {
            IsOnline = true;
        }
    }
}